package com.hqq.rabbitmq.publisher;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

/**
 * 广播消息模板的发送者
 * @author huangqiqin
 * @date 2021/04/19 00:29
 **/
@Component
public class FanoutPublisher {

    @Autowired
    private Environment env;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 发送消息
     * @param obj
     */
    public void sendFanoutMessage(Object obj){
        try {
            if (obj != null){
                // 设置消息传输格式（JSON）
                rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
                // 设置广播交换机
                rabbitTemplate.setExchange(env.getProperty("mq.fanout.exchange.name"));
                // 创建消息实例
                Message message = MessageBuilder.withBody(objectMapper.writeValueAsBytes(obj)).build();
                // 发送消息
                rabbitTemplate.convertAndSend(message);
                System.out.println("广播消息已发送：" + obj);
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }

}
